
package com.ljfiction.book.readview;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PointF;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.Scroller;

import com.lidroid.xutils.util.LogUtils;
import com.ljfiction.book.Baner.Bookchapters;
import com.ljfiction.book.Baner.ReadBaocunBean;
import com.ljfiction.book.tools.ScreenUtils;
import com.ljfiction.book.tools.SettingManager;
import com.ljfiction.book.tools.ToastUtils;
import com.ljfiction.book.tools.Tool;

import java.util.List;


/**
 * Created by admin on 2017/8/15.
 */


public abstract class BaseReadView extends View{
    protected int mScreenWidth;
    protected int mScreenHeight;

    protected PointF mTouch = new PointF();
    protected float touch_down = 0; // 当前触摸点与按下时的点的差值

    protected Bitmap mCurPageBitmap, mNextPageBitmap;
    protected Canvas mCurrentPageCanvas, mNextPageCanvas;
    protected PageFactory pagefactory = null;

    protected OnReadStateChangeListener listener;
    protected String bookId;
    public boolean isPrepared = false;
    private Context context;

    Scroller mScroller;
    private boolean isdelect;
    private ReadBaocunBean readBaocunBean;

    public BaseReadView(Context context, String bookId, List<Bookchapters.DataBean.ChapterInfoBean.ResultListBean> chaptersList,
                        OnReadStateChangeListener listener, ReadBaocunBean readBaocunBean) {
        super(context);
        this.listener = listener;
        this.bookId = bookId;
        this.context = context;
        this.readBaocunBean = readBaocunBean;
        setWillNotDraw(false);
            mScreenWidth = ScreenUtils.getScreenWidth(context);
        mScreenHeight = ScreenUtils.getScreenHeight(context);
        mCurPageBitmap = Bitmap.createBitmap(mScreenWidth, mScreenHeight, Bitmap.Config.ARGB_8888);
        mNextPageBitmap = Bitmap.createBitmap(mScreenWidth, mScreenHeight, Bitmap.Config.ARGB_8888);
        mCurrentPageCanvas = new Canvas(mCurPageBitmap);
        mNextPageCanvas = new Canvas(mNextPageBitmap);

        mScroller = new Scroller(getContext());
        pagefactory = new PageFactory(getContext(), bookId, chaptersList, readBaocunBean);
        pagefactory.setOnReadStateChangeListener(listener);

    }

    public synchronized void init() {
        if (!isPrepared) {
            try {
                //pagefactory.setBgBitmap(ThemeManager.getThemeDrawable(theme, context));
                // 自动跳转到上次阅读位置
                int[] pos = SettingManager.getInstance().getReadProgress(bookId);
                int ret = pagefactory.openBook(pos[0], new int[]{pos[1], pos[2], pos[3], pos[4]});
                LogUtils.i("上次阅读位置：chapter=" + pos[0] + " startPos=" + pos[1] + " endPos=" + pos[2]);
                 if (ret == 0) {
                    listener.onLoadChapterFailure(pos[0]);
                    return;
                }
                pagefactory.onDraw(mCurrentPageCanvas);
                pagefactory.onDraw(mNextPageCanvas);
                postInvalidate();
            } catch (Exception e) {
            }
            isPrepared = true;
        }
    }

    //是否移动了
    private Boolean isMove = false;
    //是否翻到下一页
    protected Boolean isNext = false;
    //是否取消翻页
    protected Boolean cancelPage = false;
    //是否没下一页或者上一页
    private Boolean noNext = false;
    protected int downX = 0;
    protected int downY = 0;

    protected int moveX = 0;
    private int moveY = 0;
    //翻页动画是否在执行
    private Boolean isRuning = false;
    private long et = 0;
    private boolean cancel = false;
    private boolean center = false;
    private boolean dianji = false;
    private long time = 0;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        /* if (PageFactory.getStatus() == PageFactory.Status.OPENING){
            return true;
        }*/


        int x = (int) event.getX();
        int y = (int) event.getY();
        mTouch.x = event.getX();
        mTouch.y = event.getY();
        //触摸y中间位置吧y变成屏幕高度
        if ((downY > mScreenHeight / 3 && downY < mScreenHeight * 2 / 3) || (isMove && !isNext)) {
            mTouch.y = mScreenHeight;
        }

        if (downY > mScreenHeight / 3 && downY < mScreenHeight / 2 && isNext) {
            mTouch.y = 1;
        }

        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            //如果在两秒大于2秒
            if (System.currentTimeMillis() - time < 500) {

                return false;
            }
            //获得当前的时间
            time = System.currentTimeMillis();
            downX = (int) event.getX();
            downY = (int) event.getY();
            moveX = 0;
            moveY = 0;
            isMove = false;
//            cancelPage = false;
            noNext = false;
            isNext = false;
            isRuning = false;
            if (listener.isBarhit()) {
                listener.onCenterClick();
                resetTouchPoint();
                return false;
            }
            pagefactory.onDraw(mCurrentPageCanvas);
            calcCornerXY(downX, downY);
            abortAnimation();
        } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
            final int slop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
            //判断是否移动了
            if (!isMove) {
                isMove = Math.abs(downX - x) > slop || Math.abs(downY - y) > slop;
            }
            if (isMove) {
                isMove = true;
                if (moveX == 0 && moveY == 0) {
                    //判断翻得是上一页还是下一页
                    if (x - downX > 0) {
                        isNext = false;
                    } else {
                        isNext = true;
                    }
                    cancelPage = false;
                    if (isNext) {
                        Boolean isNext = false;
                        BookStatus status = pagefactory.nextPage();
                        if (status == BookStatus.NO_NEXT_PAGE) {
                            //Tool.showToast("没有下一页啦", context);
                            isNext = false;
                        } else if (status == BookStatus.LOAD_SUCCESS) {
                            isNext = true;
                            pagefactory.onDraw(mNextPageCanvas);
                            //abortAnimation();
                        } else {
                            isNext = false;
                        }
//                        calcCornerXY(downX,mScreenHeight);
                        if (mScreenWidth / 2 > downX) {
                            calcCornerXY(mScreenWidth - downX, downY);
                        }

                        if (!isNext) {
                            noNext = true;
                            return true;
                        }
                    } else {
                        Boolean isPre = false;
                        BookStatus status = pagefactory.prePage();
                        if (status == BookStatus.NO_PRE_PAGE) {
                            Tool.showToast("没有上一页啦", context);
                            isPre = false;
                        } else if (status == BookStatus.LOAD_SUCCESS) {
                            abortAnimation();
                            pagefactory.onDraw(mNextPageCanvas);
                            isPre = true;
                        } else {
                            isPre = false;
                        }
                        //上一页滑动不出现对角
                        if (downX > mScreenWidth / 2) {
                            calcCornerXY(downX, mScreenHeight);
                        } else {
                            calcCornerXY(mScreenWidth - downX, mScreenHeight);
                        }

                        if (!isPre) {
                            noNext = true;
                            return true;
                        }
                    }
                } else {
                    //判断是否取消翻页
                    if (isNext) {
                        if (x - moveX > 0) {
                            cancelPage = true;
                        } else {
                            cancelPage = false;
                        }
                    } else {
                        if (x - moveX < 0) {
                            cancelPage = true;
                        } else {
                            cancelPage = false;
                        }
                    }
                }

                moveX = x;
                moveY = y;
                isRuning = true;
                this.postInvalidate();
            }
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
            if (!isMove) {
                cancelPage = false;

                if (downX >= pagefactory.getZidongBitmapWight() && downX <= pagefactory.getZidongBitmapWight() + ScreenUtils.getNum(context,20) && downY >= pagefactory.getZidongBitmapHeight() && downY <= pagefactory.getZidongBitmapHeight() + ScreenUtils.getNum(context,20) && pagefactory.isVip()) {
                    pagefactory.isSelectzidong = pagefactory.isSelectzidong ? false : true;
                    resetTouchPoint();
                    refreshPage();
                    return false;
                }
                if (downX >= ScreenUtils.getNum(context,82) && downX <= mScreenWidth - ScreenUtils.getNum(context,82) && downY >= mScreenHeight - ScreenUtils.getNum(context,150) && downY <= mScreenHeight - ScreenUtils.getNum(context,110) && pagefactory.isVip()) {
                    listener.tobuy(pagefactory.isSelectzidong);
                    resetTouchPoint();
                    return false;
                }
                if (downX >= (mScreenWidth-ScreenUtils.getNum(context,72))/2 && downX <= (mScreenWidth+ScreenUtils.getNum(context,72))/2&& downY >= mScreenHeight - ScreenUtils.getNum(context,220) && downY <= mScreenHeight - ScreenUtils.getNum(context,200) && pagefactory.isVip()) {
                    listener.toInvite();
                    resetTouchPoint();
                    return false;
                }
                if (downX > mScreenWidth * 9 / 10) {
                    isdelect = false;
                    for (Baocunduanping baocunduanping :
                            readBaocunBean.getContextMap().get(pagefactory.getPosition()[0]).getBaocunyeshu().get(pagefactory.getPosition()[3])) {
                        if ( downY < baocunduanping.getYuanheight()+ScreenUtils.getNum(context,5)&&downY+ScreenUtils.getNum(context,5)>baocunduanping.getLety()) {
                            listener.dianseclect(baocunduanping.getUuid(), baocunduanping.getChaptertext());
                            isdelect = true;
                            resetTouchPoint();
                            return false;
                        }
                    }

                }
                //是否点击了中间
                if (downX > mScreenWidth /5 && downX < mScreenWidth * 4 / 5 ) {
                    if (listener != null) {
                        listener.onCenterClick();
                    }
//                    mCornerX = 1; // 拖拽点对应的页脚
//                    mCornerY = 1;
//                    mTouch.x = 0.1f;
//                    mTouch.y = 0.1f;
                    return true;
                } else if (x < mScreenWidth / 2) {
                    isNext = false;
                } else {
                    isNext = true;
                }

                if (isNext) {
                    Boolean isNext = false;
                    BookStatus status = pagefactory.nextPage();
                    if (status == BookStatus.NO_NEXT_PAGE) {
                       // Tool.showToast("没有下一页啦", context);
                        isNext = false;
                    } else if (status == BookStatus.LOAD_SUCCESS) {
                        isNext = true;
                        pagefactory.onDraw(mNextPageCanvas);
                        abortAnimation();
                    } else {
                        isNext = false;
                    }
                    if (!isNext) {
                        return true;
                    }
                } else {
                    Boolean isPre = false;
                    BookStatus status = pagefactory.prePage();
                    if (status == BookStatus.NO_PRE_PAGE) {
                        Tool.showToast("没有上一页啦", context);
                        isPre = false;
                    } else if (status == BookStatus.LOAD_SUCCESS) {
                        abortAnimation();
                        pagefactory.onDraw(mNextPageCanvas);
                        isPre = true;
                    } else {
                        isPre = false;
                    }
                    calcCornerXY(mScreenWidth - downX, mScreenHeight);
                    mTouch.y = mScreenHeight;
                    if (!isPre) {
                        return true;
                    }
                }
            }

            if (cancelPage && listener != null) {
                pagefactory.toBackpage();
                //mTouchListener.cancel();
            }

            if (!noNext) {
                isRuning = true;
                startAnimation();
                this.postInvalidate();
            }
        }

        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (isRuning) {
            if (isNext) {
                calcPoints();
                drawCurrentPageArea(canvas, mCurPageBitmap);
                drawNextPageAreaAndShadow(canvas, mNextPageBitmap);
                drawCurrentPageShadow(canvas);
                drawCurrentBackArea(canvas, mCurPageBitmap);
            } else {
                calcPoints();
                drawCurrentPageArea(canvas, mNextPageBitmap);
                drawNextPageAreaAndShadow(canvas, mCurPageBitmap);
                drawCurrentPageShadow(canvas);
                drawCurrentBackArea(canvas, mNextPageBitmap);
            }
        } else {
            if (cancelPage) {
                canvas.drawBitmap(mCurPageBitmap, 0, 0, null);
            } else {
                canvas.drawBitmap(mNextPageBitmap, 0, 0, null);
            }
        }
    }

    protected abstract void drawNextPageAreaAndShadow(Canvas canvas, Bitmap bitmap);

    protected abstract void drawCurrentPageShadow(Canvas canvas);

    protected abstract void drawCurrentBackArea(Canvas canvas, Bitmap bitmap);

    protected abstract void drawCurrentPageArea(Canvas canvas, Bitmap bitmap);

    protected abstract void calcPoints();

    protected abstract void calcCornerXY(float x, float y);


    /**
     * 开启翻页
     */

    protected abstract void startAnimation();


    /**
     * 停止翻页动画（滑到一半调用停止的话  翻页效果会卡住 可调用#{restoreAnimation} 还原效果）
     */

    protected abstract void abortAnimation();


    /**
     * 还原翻页
     */

    protected abstract void restoreAnimation();

    protected abstract void setBitmaps(Bitmap mCurPageBitmap, Bitmap mNextPageBitmap);

    public abstract void setTheme(int theme);


    /**
     * 复位触摸点位
     */

    protected void resetTouchPoint() {
        mTouch.x = 0.1f;
        mTouch.y = 0.1f;
        touch_down = 0;
        calcCornerXY(mTouch.x, mTouch.y);
    }

    public void jumpToChapter(int chapter) {
        resetTouchPoint();
        pagefactory.openBook(chapter, new int[]{0, 0, 0, 0});
        pagefactory.onDraw(mCurrentPageCanvas);
        pagefactory.onDraw(mNextPageCanvas);
        postInvalidate();
    }

    public void nextPage() {
        BookStatus status = pagefactory.nextPage();
        if (status == BookStatus.NO_NEXT_PAGE) {
            //Tool.showToast("没有下一页啦", context);
            return;
        } else if (status == BookStatus.LOAD_SUCCESS) {
            if (isPrepared) {
                pagefactory.onDraw(mCurrentPageCanvas);
                pagefactory.onDraw(mNextPageCanvas);
                postInvalidate();
            }
        } else {
            return;
        }

    }

    /*
    * 刷新页面
    * */
    public void refreshPage() {
        if (isPrepared) {
            pagefactory.onDraw(mCurrentPageCanvas);
            pagefactory.onDraw(mNextPageCanvas);
            postInvalidate();
        }
    }

    public void prePage() {
        BookStatus status = pagefactory.prePage();
        if (status == BookStatus.NO_PRE_PAGE) {
            Tool.showToast("没有上一页啦", context);
            return;
        } else if (status == BookStatus.LOAD_SUCCESS) {
            if (isPrepared) {
                pagefactory.onDraw(mCurrentPageCanvas);
                pagefactory.onDraw(mNextPageCanvas);
                postInvalidate();
            }
        } else {
            return;
        }
    }

    public synchronized void setFontSize(final int fontSizePx) {
        resetTouchPoint();
        pagefactory.setTextFont(fontSizePx);
        if (isPrepared) {
            pagefactory.onDraw(mCurrentPageCanvas);
            pagefactory.onDraw(mNextPageCanvas);
           /* SettingManager.getInstance().saveFontSize(bookId, fontSizePx);
            SettingManager.getInstance().saveFontSize(fontSizePx);*/
            postInvalidate();
        }
    }

    public synchronized void setBeijing(final int position) {
        resetTouchPoint();
        pagefactory.setBeijing(position);
        if (isPrepared) {
            pagefactory.onDraw(mCurrentPageCanvas);
            pagefactory.onDraw(mNextPageCanvas);
           /* SettingManager.getInstance().saveFontSize(bookId, fontSizePx);
            SettingManager.getInstance().saveFontSize(fontSizePx);*/
            postInvalidate();
        }
    }

    public synchronized void setTextColor(int textColor, int titleColor) {
        resetTouchPoint();
        pagefactory.setTextColor(textColor, titleColor);
        if (isPrepared) {
            pagefactory.onDraw(mCurrentPageCanvas);
            pagefactory.onDraw(mNextPageCanvas);
            postInvalidate();
        }
    }

    public void setBattery(int battery) {
        pagefactory.setBattery(battery);
        if (isPrepared) {
            pagefactory.onDraw(mCurrentPageCanvas);
            pagefactory.onDraw(mNextPageCanvas);
            postInvalidate();
        }
    }



    public void setPosition(int[] pos) {
        int ret = pagefactory.openBook(pos[0], new int[]{pos[1], pos[2], pos[3], pos[4]});
        if (ret == 0) {
            listener.onLoadChapterFailure(pos[0]);
            return;
        }
        pagefactory.topagenow();
        pagefactory.onDraw(mCurrentPageCanvas);
        pagefactory.onDraw(mNextPageCanvas);
        postInvalidate();
        isPrepared = true;
    }

    public int[] getReadPos() {
        return pagefactory.getPosition();
    }

    public int getFontSize() {
        return pagefactory.getTextFont();
    }

    public String getHeadLine() {
        return pagefactory.getHeadLineStr().replaceAll("@", "").replaceAll(" ", "");
    }
public void recycleBitmap(){
    if (pagefactory != null) {
        pagefactory.recycle();
    }

    if (mCurPageBitmap != null && !mCurPageBitmap.isRecycled()) {
        mCurrentPageCanvas=null;
        mCurPageBitmap.recycle();
        mCurPageBitmap = null;
    }

    if (mNextPageBitmap != null && !mNextPageBitmap.isRecycled()) {
        mNextPageCanvas=null;
        mNextPageBitmap.recycle();
        mNextPageBitmap = null;
    }
}
    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (pagefactory != null) {
            pagefactory.recycle();
        }

        if (mCurPageBitmap != null && !mCurPageBitmap.isRecycled()) {
            mCurPageBitmap.recycle();
            System.gc();
            System.runFinalization();
            System.gc();
            LogUtils.d("mCurPageBitmap recycle");
        }

        if (mNextPageBitmap != null && !mNextPageBitmap.isRecycled()) {
            mNextPageBitmap.recycle();
            System.gc();
            System.runFinalization();
            System.gc();
            LogUtils.d("mNextPageBitmap recycle");
        }
    }

    public void setauthorImage(Bitmap resource) {
        pagefactory.setauthorImage(resource);
    }
}

